#include<iostream>
#include<queue>
#include<string>
#include<sstream>
#include<cstring>
using namespace std;
const int N = 510;
int stop[N];
int g[N][N];
int dis[N];
int n, m;
void bfs()
{
	queue<int>q;
	memset(dis, 0x3f, sizeof(dis));
	q.push(1);
	dis[1] = 0;
	while (q.size()) {
		int t = q.front();
		q.pop();
		for (int i = 1; i <= n; i++) {
			if (g[t][i] && dis[i] > dis[t] + 1) {
				dis[i] = dis[t] + 1;
				q.push(i);
			}
		}
	}
}
int main()
{
	cin >> m >> n;
	string line;
	getline(cin, line);
	while (m--) {
		getline(cin, line);
		stringstream ss(line);
		int cnt = 0;
		memset(stop, 0, sizeof(stop));
		int x;
		while (ss >> x) {
			stop[cnt++] = x;
		}
		for (int i = 0; i < cnt; i++) {
			for (int j = i + 1; j < cnt; j++) {
				g[stop[i]][stop[j]] = 1;
			}
		}
	}
	bfs();
	if (dis[n] == 0x3f3f3f3f) {
		cout << "NO" << endl;
		return 0;
	}
	cout << max(0, dis[n] - 1) << endl;
	return 0;	
}